# app/routes/hardware-windows.py
from flask import Blueprint, jsonify
import wmi
import pythoncom

def get_hardware_info():
    try:
        pythoncom.CoInitialize()  # 初始化 COM 环境
        WMI = wmi.WMI()        
        hardware_info = {}

        # 硬盘信息
        disks = []
        for diskinfo in WMI.Win32_DiskDrive():
            if '虚拟' not in diskinfo.Caption:
                size_gb = str(round(int(diskinfo.Size) / (1024 ** 3), 2)) + "GB"  # 将字节转换为GB，并保留两位小数
                disks.append({
                    '型号': diskinfo.Model,
                    '序列号': diskinfo.SerialNumber,
                    '硬盘大小': size_gb
                })
        hardware_info['硬盘'] = disks

        # CPU信息
        cpus = []
        for cpuinfo in WMI.Win32_Processor():
            cpus.append({
                '名称': cpuinfo.Name,
                '制造商': cpuinfo.Manufacturer,
                '序列号': cpuinfo.SerialNumber,
                '核心数': cpuinfo.NumberOfCores
            })
        hardware_info['CPU'] = cpus

        # 主板信息
        boards = []
        for boardinfo in WMI.Win32_BaseBoard():
            boards.append({
                '制造商': boardinfo.Manufacturer,
                '产品号': boardinfo.Product,
                '序列号': boardinfo.SerialNumber
            })
        hardware_info['主板'] = boards

        # 网卡信息
        network_adapters = []
        for NetworkAdapter in WMI.Win32_NetworkAdapter():
            if NetworkAdapter.MACAddress and not is_virtual_network_adapter(NetworkAdapter):
                network_adapters.append({
                    '名称': NetworkAdapter.Name,
                    '制造商': NetworkAdapter.Manufacturer,
                    'MAC地址': NetworkAdapter.MACAddress,
                    '状态': get_connection_status(NetworkAdapter.NetConnectionStatus)
                })
        hardware_info['网卡'] = network_adapters

        # BIOS信息
        bioses = []
        for biosinfo in WMI.Win32_BIOS():
            bioses.append({
                '名称': biosinfo.Name,
                '制造商': biosinfo.Manufacturer,
                '序列号': biosinfo.SerialNumber
            })
        hardware_info['BIOS'] = bioses

        # 内存信息
        memories = []
        for memoryinfo in WMI.Win32_PhysicalMemory():
            size_gb = str(round(int(memoryinfo.Capacity) / (1024 ** 3), 2)) + "GB" # 将字节转换为GB，并保留两位小数
            memories.append({
                '制造商': memoryinfo.Manufacturer,
                '型号': memoryinfo.PartNumber,
                '序列号': memoryinfo.SerialNumber,
                '内存大小': size_gb
            })
        hardware_info['内存'] = memories
        return hardware_info
    except Exception as e:
            # 捕获所有未处理的异常，并返回错误信息
            return {"error": "hardware-windows"+str(e)}
    finally:
        pythoncom.CoUninitialize()  # 确保在结束时清理


def is_virtual_network_adapter(adapter):
    """
    判断是否为虚拟网卡。
    :param adapter: Win32_NetworkAdapter 对象
    :return: 如果是虚拟网卡返回 True，否则返回 False
    """
    # 检查 Name 或 Manufacturer 是否包含虚拟网卡的常见标识符
    name = adapter.Name.lower() if adapter.Name else ''
    manufacturer = adapter.Manufacturer.lower() if adapter.Manufacturer else ''

    virtual_keywords = ['vmware', 'microsoft', 'virtualbox', 'hyper-v']

    if any(keyword in name for keyword in virtual_keywords) or any(keyword in manufacturer for keyword in virtual_keywords):
        return True

    return False
def get_connection_status(status_code):
    """
    根据 NetConnectionStatus 返回适配器的状态描述。
    :param status_code: Win32_NetworkAdapter.NetConnectionStatus 的值
    :return: 状态描述字符串
    """
    statuses = {
        0: "未连接",
        1: "正在连接",
        2: "已连接",
        7: "连接受限"
    }
    return statuses.get(status_code, "未知状态")